package com.nuaa.ange.controller;

import com.nuaa.ange.dto.ArticleDto;
import com.nuaa.ange.utils.ElasticSearchUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @description
 * @author 玦离
 * @date 2023/1/1 20:06
 */

@RestController
@Api(tags = "搜索引擎相关接口")
@RequestMapping("/elasticsearch")
public class ElasticSearchController extends BaseController{

    @ApiOperation(value = "得到搜索内容")
    @GetMapping("/search")
    public List<ArticleDto> matchQuery(@RequestParam("userId") int userId, @RequestParam("searchContent") String searchContent) throws IOException {
        QueryBuilder queryBuilder = QueryBuilders.multiMatchQuery(searchContent,"tags","title","content")
                .field("tags", 5)
                .field("title", 3)
                .field("content",1);
        List<SearchHit> hits = ElasticSearchUtil.query("article_index", queryBuilder);
        List<ArticleDto> allArticleUser = new ArrayList<>();
        for (SearchHit hit : hits) {
            int articleId = (int) hit.getSourceAsMap().get("id");
            System.out.println(articleId);
            ArticleDto articleUser = articleService.getArticleDtoById(userId, articleId);
            allArticleUser.add(articleUser);
        }
        return allArticleUser;
    }


}
